package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.vo.ErrorResult;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.scanner.Constant;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {
    @DubboReference
    UserService userService;
 @Autowired
   SmsTemplate smsTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public Long save(User user) {
        return userService.save(user
        );
    }

    public User findByPhone(String phone) {
        return userService.findByPhone(phone);
    }

    public void sendCode(String phone) {
    //生成一个随机密码
        String code = RandomUtil.randomNumbers(6);
        //todo 现在是在开发阶段，只需要设定验证码123456
        //constan...inii，，，初始密码123456
        code= ConstantUtil.INIT_PASSWORD;
    //调用smstemplate发送短信
        //todo 开发阶段，项目上线可以开启这个注释
    //     smsTemplate.sendSms(phone,code);

    //3.将验证码就放入redis中时效为u分钟
stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,code, Duration.ofMinutes(5));
    }

    public ResponseEntity regAndLogin(Map<String, String> map) {
    //1获取用户提交过来的手机号和验证码
         String phone = map.get("phone");
        String verificationcode = map.get("verificationcode");

        // 判断用户的验证码是否和redis中的一致
        final String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        // 3若不一致，生成响应码，提示验证码输出错误
        if (!StrUtil.equals(verificationcode,redisCode)){
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
    //    4若一致，通过手机号查询用户，返回user
        User user = userService.findByPhone(phone);

        //    5判断用户是否存在
        boolean isNew;
    //    5.1若存在就是老用户isnew=false
        if (user!=null){
            isNew=false;
        }else {
            isNew=true;
        //    保存用户
            user=new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long id = userService.save(user);
            user.setId(id);
        }
    //生成token 为了以后登录方便，将token 和用户信息放入redis，设置时效为30天，删除短信验证码
        // 为了安全起见，将密码设定为null
        user.setPassword(null);

        String token = JwtUtil.createToken(BeanUtil.beanToMap(user));
    //    将token放入redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, JSON.toJSONString(user), Duration.ofDays(30));
    //    删除短信验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);
    //    返回客户端数据
        Map<String ,Object> responseMap=new HashMap<>();
        responseMap.put("isNew",isNew);
        responseMap.put("token",token);
        return  ResponseEntity.ok(responseMap);
    }
}
